//角色管理
import * as React from 'react';
import {
  TreeSelect,
  Modal,
  Row,
  Col,
  DatePicker,
  Menu,
  Steps,
  Dropdown,
  Icon,
  Input,
  Table,
  Button,
  Form,
  message,
  InputNumber,
  notification,
} from 'antd';

import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { formatTreeData } from '../../components/commonAips';
import axios from 'axios';
import Api from '../../services/apis';
import styles from "./style.less";

const confirm = Modal.confirm;
//时间组件
const { RangePicker } = DatePicker;
const Step = Steps.Step;
const FormItem = Form.Item;
import moment from 'moment';
import 'moment/locale/zh-cn';
//获取默认时间并在下面转换为moment格式
const nowYear = new Date().getFullYear();
const startTime = `${nowYear}-01-01`;
const [endTimeMonth, endTimeDay] = [
  new Date().getMonth() + 1 < 10 ? `0${new Date().getMonth() + 1}` : new Date().getMonth() + 1,
  new Date().getDate() < 10 ? `0${new Date().getDate()}` : new Date().getDate(),
];
const endTime = `${nowYear}-${endTimeMonth}-${endTimeDay}`;
@connect(({ user, project, activities, chart, loading }) => ({
  currentUser: user.currentUser,
  currentUserLoading: loading.effects['user/fetchCurrent']
}))
class roleManagement extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
      roleId: '',
      roleCode: '',
      roleName: '',
      roleDesc: '',
      remark: '',
      current: 1,
      rolePowerCurrnet: 1,
      modalVisible: false,
      modifyVisible: false,
      selectedArr: [],
      selectedId: [],
      roleTableData: [],
      powerTableData: [],
    };
  }

  sendData = () => {
    const that = this;

    axios
      .post(Api.umGetRoleList, {
        roleName: this.state.name,
      })
      .then(function (data) {
        if (data.data.length == 0) {
          message.warning('暂无数据');
        } else {
          data.data.forEach((d, i, arr) => {
            d.key = i;
            d.deleText = d.stateCode == 0 ? '禁用' : '启用';
          });
          that.setState({
            roleTableData: data.data,
          });
        }
      });
  };

  componentWillMount() {
    const that = this;

    //获取表格数据
    that.sendData();

    //获取权限列表
    axios
      .post(Api.umGetFunctionList, {
        currentPage: this.state.current,
      })
      .then(function (data) {
        if (data.data.list && data.data.list.length != 0) {
          data.data.list.forEach((d, i, arr) => {
            d.key = i;
          });
          that.setState({
            powerTableData: data.data.list,
            current: data.data.currentPage,
            totalSize: data.data.totalPage,
          });
        }
      });
  }

  resetForm() {
    this.setState({
      name: '',
    });
  }

  //添加角色
  addRole() {
    const that = this;
    if (!that.state.roleCode) {
      notification.destroy();
      notification['warning']({
        message: '请填写角色编码！',
      });
    } else if (!that.state.roleName) {
      notification.destroy();
      notification['warning']({
        message: '请填写角色名称！',
      });
    } else if (!that.state.roleDesc) {
      notification.destroy();
      notification['warning']({
        message: '请填写角色说明！',
      });
    } else if (!that.state.remark) {
      notification.destroy();
      notification['warning']({
        message: '请填写备注！',
      });
    } else {
      axios
        .post(Api.umAddRole, {
          roleCode: this.state.roleCode,
          roleName: this.state.roleName,
          roleDesc: this.state.roleDesc,
          remark: this.state.remark,
          funArray: this.state.selectedId.join(','),
        })
        .then(function (data) {
          if (data.data.code == 1 || data.data.code == 3) {
            notification.destroy();
            notification['success']({
              message: data.data.msg,
            });
            that.sendData();
            this.setModalVisible(false);
          } else if (data.data.code == 2) {
            notification.destroy();
            notification['warning']({
              message: data.data.msg,
            });
          } else if (data.data.code == 0) {
            notification.destroy();
            notification['error']({
              message: data.data.msg,
            });
          } else if (data.data.code == 4) {
            notification.destroy();
            notification['error']({
              message: data.data.msg,
            });
          }
        });
    }
  }
  frozenUser = (id, opt) => {
    let that = this;
    confirm({
      title: opt == '禁用' ? '禁用确认' : '启用确认',
      content: opt == '禁用' ? '确认要禁用该用户？' : '确认要启用该用户？',
      onOk() {
        axios
          .post(Api.umUpdateRoleState, {
            roleId: id,
          })
          .then(function (data) {
            if (data.data.code == 1) {
              notification.destroy();
              notification['success']({
                message: data.data.msg,
              });
              that.sendData();
            } else if (data.data.code == 0) {
              notification.destroy();
              notification['error']({
                message: data.data.msg,
              });
            }
          });
      },
      onCancel() { },
    });
  };

  //获取用户权限
  getPower = id => {
    let that = this;
    that.setState({ roleId: id, rolePowerCurrnet: 1 });
    let param = new URLSearchParams();
    param.append('roleId', id);

    axios
      .post(Api.umGetFunListByRole, {
        roleId: id,
      })
      .then(function (data) {
        if (data.data.length > 0) {
          let selectedArr = [];
          data.data.forEach((d, i, arr) => {
            d.key = i;
            if (d.roleHaveFunction) {
              selectedArr.push(i);
            }
          });
          that.setState({
            selectedArr: selectedArr,
            powerTableDataByRole: data.data,
            totalSize: data.data.length,
          });

          that.setmodifyVisible(true);
        }
      });
  };

  //修改权限
  changePower = () => {
    let that = this;

    axios
      .post(Api.umGetFunListByRole, {
        roleId: that.state.roleId,
        funArray: that.state.selectedId.join(','),
      })
      .then(function (data) {
        if (data.data.code == 1) {
          notification.destroy();
          notification['success']({
            message: data.data.msg,
          });
          that.sendData();
          this.setmodifyVisible(false);
        } else if (data.data.code == 0) {
          notification.destroy();
          notification['error']({
            message: data.data.msg,
          });
        }
      });
  };

  setModalVisible(modalVisible) {
    this.setState({
      modalVisible: modalVisible,
      selectedArr: [],
      roleCode: '',
      roleName: '',
      roleDesc: '',
      remark: '',
      funArray: [],
    });
  }
  setmodifyVisible = modifyVisible => {
    this.setState({
      modifyVisible: modifyVisible,
      funArray: [],
    });
  };
  changeName = e => {
    this.setState({ name: e.target.value });
  };

  addRoleCode = e => {
    this.setState({ roleCode: e.target.value });
  };

  addRoleName = e => {
    this.setState({ roleName: e.target.value });
  };

  addRoleDesc = e => {
    this.setState({ roleDesc: e.target.value });
  };

  addRemark = e => {
    this.setState({ remark: e.target.value });
  };

  powerPageChange = (page, pageSize) => {
    this.setState({ rolePowerCurrnet: page });
  };

  //选中表格行
  changeSelected = (selectedRowKeys, selectedRows) => {
    let selectedId = [];
    selectedRows &&
      selectedRows.forEach((d, i, arr) => {
        selectedId.push(d.functionId);
      });

    this.setState({ selectedArr: selectedRowKeys, selectedId: selectedId });
  };

  render() {
    let that = this;
    const {
      currentUserLoading,
    } = this.props;
    //表头
    const columns = [
      {
        title: '角色',
        dataIndex: 'roleName',
        key: 'roleName',
      },
      {
        title: '描述',
        dataIndex: 'roleDesc',
        key: 'roleDesc',
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        width: 180,
        render: (text, item, index) => (
          <div key={index}>
            <a href="javascript:;"
              onClick={() => {
                that.getPower(item.roleId);
              }}
            >
              修改权限
            </a>&emsp;
            <a href="javascript:;"
              onClick={() => {
                that.frozenUser(item.roleId, item.deleText);
              }}
            >
              {item.deleText}
            </a>
          </div>
        ),
      },
    ];

    //权限表头
    const powerColumns = [
      {
        title: '权限名称',
        dataIndex: 'functionName',
        key: 'functionName',
      },
      {
        title: '管理编码',
        dataIndex: 'functionCode',
        key: 'functionCode',
      },
      {
        title: '描述',
        dataIndex: 'remark',
        key: 'remark',
      },
      {
        title: '创建日期',
        dataIndex: 'modifyDateStr',
        key: 'modifyDateStr',
      },
    ];

    const rowSelection = {
      selectedRowKeys: this.state.selectedArr,
      onChange: (selectedRowKeys, selectedRows) => {
        this.changeSelected(selectedRowKeys, selectedRows);
      },
    };

    return (
      <PageHeaderWrapper
        loading={currentUserLoading}
      >
        <div className="mainContainer">
          <div className='contentHeader'>
            <div className="contentHeaderTitle">
              <p>角色管理</p>
              <p>ROLE MANAGEMENT</p>
            </div>
          </div>
          <div className='mrb15'>
            <Form layout="inline" align='center'>
                <FormItem>
                    <span className="label">角色名称：</span>
                    <Input
                      value={this.state.name}
                      onChange={this.changeName.bind(this)}
                      data-inp="zldz"
                      placeholder="请输入角色名称"
                    />
                </FormItem>
                <Row gutter={24} style={{ textAlign: 'center'}}>
                    <Button icon='search' type="primary" className="evfilterbtn" onClick={this.sendData}>
                      查询
                    </Button>
                    &emsp;
                    <Button
                      onClick={this.resetForm.bind(this)}
                      type="primary"
                      htmlType="reset"
                      className="evfilterbtn" icon="reload"
                    >
                      重置
                  </Button>
                  &emsp;
                  <Button
                    type="primary"
                    onClick={() => this.setModalVisible(true)}
                    htmlType="reset" icon="plus-circle"
                  >
                    新增
                </Button>
              </Row>
            </Form>
          </div>

          <Row className="choicedBox">
            <Table
              bordered={true}
              scroll={{x:true}}
              align={'center'}
              columns={columns}
              dataSource={this.state.roleTableData}
            />
          </Row>

          <Modal
            title="基本信息"
            wrapClassName="vertical-center-modal"
            visible={this.state.modalVisible}
            onOk={this.addRole.bind(this)}
            onCancel={() => this.setModalVisible(false)}
            width={830}
          >
            <Row gutter={24} className={styles.modalForm}>
              <Col span={8}>
              <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>角色编码
              </span>
                <Input
                  value={this.state.roleCode}
                  data-inp="zdbh"
                  onChange={this.addRoleCode.bind(this)}
                  placeholder=""
                />
              </Col>

              <Col span={8}>
              <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>角色名称
              </span>
                <Input
                  value={this.state.roleName}
                  onChange={this.addRoleName.bind(this)}
                  data-inp="zldz"
                  placeholder=""
                />
              </Col>
              <Col span={8}>
              <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>角色说明
              </span>
                <Input
                  value={this.state.roleDesc}
                  data-inp="zdbh"
                  onChange={this.addRoleDesc.bind(this)}
                  placeholder=""
                />
              </Col>

              <Col span={8}>
              <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>备注
              </span>
                <Input
                  value={this.state.remark}
                  onChange={this.addRemark.bind(this)}
                  data-inp="zldz"
                  placeholder=""
                />
              </Col>
            </Row>

            <Row>
              <Col className="pull-left w-1600 labelbox" style={{ verticalAlign: 'top' }}>
                <span className="label" style={{ verticalAlign: 'top' }}>
                  权限
              </span>
                <Table
                  size="small"
                  bordered={true}
                  align={'center'}
                  columns={powerColumns}
                  dataSource={this.state.powerTableData}
                  rowSelection={rowSelection}
                  pagination={{
                    defaultPageSize: that.state.pageSize,
                    current: that.state.current,
                    onChange: that.pageChange,
                    total: that.state.totalSize,
                    showTotal: total => `共 ${total} 项`
                  }}
                  style={{ display: 'inline-block' }}
                />
              </Col>
            </Row>
          </Modal>

          <Modal
            title="修改权限"
            wrapClassName="vertical-center-modal"
            visible={this.state.modifyVisible}
            onOk={this.changePower}
            onCancel={() => this.setmodifyVisible(false)}
            width={830}
          >
            <Row>
              <Col className="pull-left w-1600 labelbox">
                <span className="label" style={{ verticalAlign: 'top' }}>
                  权限
              </span>
                <Table
                  size="small"
                  bordered={true}
                  align={'center'}
                  columns={powerColumns}
                  dataSource={this.state.powerTableDataByRole}
                  rowSelection={rowSelection}
                  pagination={{
                    defaultPageSize: 5,
                    current: that.state.rolePowerCurrnet,
                    total: that.state.totalSize,
                    onChange: that.powerPageChange,
                    showTotal: total => `共 ${total} 项`
                  }}
                  style={{ display: 'inline-block' }}
                />
              </Col>
            </Row>
          </Modal>
        </div>
      </PageHeaderWrapper>
    );
  }
}
export default roleManagement;
